<?php


namespace app\controller\admin;


use app\common\OrderStatus;
use app\models\user\DepartmentModel;
use app\models\user\StaffModel;
use think\facade\Db;

class StaffController extends BaseAdminController
{

    function setSearch()
    {
        return [
            '=' => ['department_id'],
            'eq_date' => ['entry_time', 'full_time'],
            '%like%' => ['name', 'mobile'],
        ];
    }

    function setSort()
    {
        return [
            'department_attr' => 'department_id'
        ];
    }

    public function getList()
    {
        try {
            $where = $this->searchWhere;
            $orderBy = $this->orderBy;
            $sort = $this->sort;
            $list = StaffModel::where($where)
                ->order($orderBy, $sort)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $departmentInfo = DepartmentModel::find($v['department_id']);
                $v['department_attr'] = $departmentInfo['name'];
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getStaffInfo()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $info = StaffModel::find($id);
            Db::commit();
            return $this->success($info);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function add()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            StaffModel::create($data);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function edit()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            StaffModel::update($data);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function del()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            if ($id <= 0) {
                throw new \Exception('非法请求');
            }
            $info = StaffModel::find($id);
            if (!$info) {
                throw new \Exception('信息不存在');
            }
            $info->delete();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


}